<script setup>
import {get, post} from '@/utils/request';
import {ref, reactive, onMounted} from "vue";
import * as echarts from 'echarts';
import {parseMonth} from "@/utils/DateUtil.js";
import {useRouter} from "vue-router";
import {showSuccessToast} from "vant";

const router = useRouter();

let category = ref(null)
let purchaser = ref(null)


const onClickLeft = () => history.back();

let categoryOption = {
  title: {
    text: '',
    textAlign: 'auto',

  },
  tooltip: {
    trigger: 'item',
    formatter: '{a}:{b}总拉货{c}KG'
  },
  //类型分类
  legend: {},
  series: [
    {
      name: '采购商',
      type: 'pie',
      radius: '50%',
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};

let purchaserOption = {
  title: {
    text: '',
    textAlign: 'auto',

  },
  tooltip: {
    trigger: 'item',
    formatter: '{a}:{b}总送货{c}KG'
  },
  //类型分类
  legend: {},
  series: [
    {
      name: '采购商',
      type: 'pie',
      radius: ['40%', '70%'],
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};

const date = new Date();
let year = ref(date.getFullYear());
let month = ref(parseMonth(date.getMonth()));
let prefixMonth = ref(null);
let myechartsCategory;
let myechartsPurchaser;
onMounted(async () => {
  myechartsCategory = echarts.init(category.value);

  //请求统计数据，从后端请求的数据
  let res = await get("/api/process/monthStatistics", {
    ym: date.getFullYear() + "-" + (parseMonth(date.getMonth()))
  });
  categoryOption.series[0].data = res.data.purchaserReceived;  //数据
  myechartsCategory.setOption(categoryOption)
  myechartsCategory.on('click', params => {
    router.push({
      name: 'processHome', query: {
        name: params.name,
        category: 1,
        activeTab: activeTab.value,
        searchDate: searchDate.value
      }
    })
  })

  myechartsPurchaser = echarts.init(purchaser.value);
  purchaserOption.series[0].data = res.data.purchaserSend;  //数
  myechartsPurchaser.setOption(purchaserOption)
  myechartsPurchaser.on('click', params => {
    router.push({
      name: 'processHome', query: {
        name: params.name,
        category: 2,
        activeTab: activeTab.value,
        searchDate: searchDate.value
      }
    })
  })
})

let activeTab = ref('月统计');
const showCalendar = ref(false);
const searchDate = ref([date.getFullYear(), parseMonth(date.getMonth())]);

const onConfirm = async ({selectedValues}) => {
  showCalendar.value = false;

  let res = await get(selectedValues.length == 1 ? "/api/process/yearStatistics" : "/api/process/monthStatistics", {
    ym: selectedValues.join('-'),
  });
  categoryOption.series[0].data = res.data.purchaserReceived;  //数据
  myechartsCategory.setOption(categoryOption, true)


  let myechartsPurchaser = echarts.init(purchaser.value);
  purchaserOption.series[0].data = res.data.purchaserSend;  //数
  myechartsPurchaser.setOption(purchaserOption, true)
  year.value = selectedValues[0];
  if (selectedValues.length > 1) {
    month.value = selectedValues[1];
  } else {
    month.value = -1;
  }
  onSearch();
};

let columnsType = ref(['year', 'month'])

const onClickTab = async ({title}) => {
  console.log(activeTab.value, title)

  if (activeTab.value === title) {
    return
  }
  activeTab.value = title;
  if (title === '月统计') {
    columnsType.value = ['year', 'month']
    searchDate.value = [date.getFullYear(), parseMonth(date.getMonth())]
  }
  if (title === '总统计') {
    columnsType.value = ['year']
    searchDate.value = [date.getFullYear()]
  }


  if (columnsType.value.length <= 1) {
    prefixMonth.value = month.value;
    month.value = -1;
  } else {
    month.value = prefixMonth.value
    prefixMonth.value = null;
  }

  let res = await get(columnsType.value.length == 1 ? "/api/process/yearStatistics" : "/api/process/monthStatistics", {
    ym: columnsType.value.length == 1 ? '-1' : year.value + "-" + month.value,
  });
  categoryOption.series[0].data = res.data.purchaserReceived;  //数据
  myechartsCategory.setOption(categoryOption, true)
  let myechartsPurchaser = echarts.init(purchaser.value);
  purchaserOption.series[0].data = res.data.purchaserSend;  //数
  myechartsPurchaser.setOption(purchaserOption, true)
  onSearch();
}

const resData = reactive({
  search: "",
  processData: []
})
const loading = ref(false);

const onSearch = () => {
  post("/api/process/listByPurchasers", {
    ym: month.value == '-1' ? -1 : year.value + "-" + month.value,
    key: resData.search
  }).then((res) => {
    resData.processData = res.data;
    loading.value = false
    loadingRefresh.value = false;
  })
}
const loadingRefresh = ref(false);

// 下拉刷新
const onRefresh = () => {
  onSearch()
};
onRefresh();


const settlement = (name) => {
  get("/api/process/settlement", {
    purchaser: name
  }).then((res) => {
    showSuccessToast("结算成功");
    onRefresh();
  })
}
</script>

<template>
  <div id="process-statistics">
    <div class="title">
      <van-nav-bar title="统计" left-text="返回" @click-left="onClickLeft"></van-nav-bar>
    </div>
    <van-tabs @click-tab="onClickTab">
      <van-tab title="月统计" name="月统计"></van-tab>
      <van-tab title="总统计" name="总统计"></van-tab>
    </van-tabs>
    <div style="text-align: right;margin-right: 5px;">
      <van-button v-if="month!==-1" block type="primary" shape="circle" icon="calendar-o" @click="showCalendar=true">
        选择日期
      </van-button>
    </div>
    <div class="main">
      <h4>{{ month == -1 ? "总" : year + "年" + month + '月' }}统计拉货统计</h4>
      <div id="category" ref="category"></div>
      <h4 style="margin-top: 50px;">{{ month == -1 ? "总" : year + "年" + month + '月' }}统计送货统计</h4>
      <div id="purchaser" ref="purchaser"></div>
    </div>
    <div class="search">
      <van-search v-model="resData.search" placeholder="请输入搜索关键词" @search="onSearch">
      </van-search>
    </div>
    <div class="records">
      <van-pull-refresh v-model="loadingRefresh" @refresh="onRefresh">

        <van-card
            :title="'采购商:'+item.name"
            v-for="item in resData.processData"
        >

          <template #price>
            <div>
              总拉:{{ item.received }}KG
            </div>
            <div>
                  <span>
                总送:{{ item.send }}KG
              </span>
            </div>
            <div>未归还: <span style="color:red;">
              {{ item.remaining }}KG
            </span></div>
          </template>
          <template #footer>
            <van-button
                hairline
                type="primary"
                @click.stop="settlement(item.name)"
                size="small">结算
            </van-button>
          </template>
        </van-card>

      </van-pull-refresh>
    </div>
    <van-popup v-model:show="showCalendar" position="bottom">

      <van-date-picker v-model="searchDate"
                       :title="columnsType.length==1?'选择年':'选择年月'"
                       @confirm="onConfirm"
                       @cancel="showCalendar = false"
                       :columns-type="columnsType"
      />
    </van-popup>
  </div>
</template>

<style scoped>
.title {
  text-align: center;
}

#category {
  height: 50vh;
}

#purchaser {
  height: 50vh;
}

.main {

  padding: 10px;

  border-radius: 5px;
  margin-top: 10px;
}
</style>